<template>
  <div class="order combground">
    <div class="container">
      <div class="local cursor" @click="$router.go(-1)">
        <img src="~/assets/images/local.png" alt="" />
        <span>返回上一级</span>
      </div>
      <div class="comtitle">
        <h2 class="comh2">确认订单信息</h2>
      </div>
      <div class="content">
        <div class="receiver">
          <div class="title-and-new">
            <p class="title">收货人信息</p>
            <div class="new" @click="showAddress = true">新增收货地址+</div>
          </div>
          <div class="address-list clearfix">
            <div
              class="item transition cursor"
              v-for="(item, index) in addressList"
              :key="index"
              :class="addressChosen == item.address_id ? 'active' : ''"
              @click="selectAddress(item.address_id)"
            >
              <div class="name">
                {{ item.real_name }}
                <span v-if="item.is_default" class="default">默认地址</span>
              </div>
              <div class="phone">{{ item.phone }}</div>
              <div class="company">{{ item.company }}</div>
              <div class="address">
                {{ item.province }}{{ item.city }}{{ item.district
                }}{{ item.detail }}
              </div>
              <div class="checkbox">
                <div class="checkItem transition"></div>
              </div>
            </div>
          </div>
          <div class="address-empty" v-if="addressList.length === 0">
            目前还未设置收货地址，请先设置收货地址
          </div>
        </div>

        <div class="checklist">
          <p class="title">商品清单</p>
          <div class="item" v-for="(item, index) in info.list" :key="index">
            <div class="merchant-and-number" v-if="item.mer_id !== 0">
              <p class="merchant">
                商家：{{ item.product_list[0] && item.product_list[0].mer.mer_name }}
              </p>
            </div>
            <Table class="table-head">
              <table-column label="商品信息" align="center" width="350" />
              <table-column label="商品单价" align="center" />
              <table-column label="数量" align="center" />
              <table-column label="小计" align="center" />
            </Table>
            <Table :data="item.product_list" border :show-header="false">
              <table-column
                prop="name"
                label="商品信息"
                align="center"
                width="350"
              >
                <template v-slot="{ row }">
                  <div class="table-name">
                    <img :src="row.product.image" alt="" class="pic" />
                    <p class="name">{{ row.product.store_name }}</p>
                  </div>
                </template>
              </table-column>
              <table-column prop="price" label="商品单价" align="center">
                <template v-slot="{ row }">
                  <div class="table-price">￥{{ row.price }}</div>
                </template>
              </table-column>
              <table-column prop="quantity" label="数量" align="center">
                <template v-slot="{ row }">
                  <div class="table-quantity">×{{ row.cart_num }}</div>
                </template>
              </table-column>
              <table-column prop="total" label="小计" align="center">
                <template v-slot="{ row }">
                  <div class="table-total">￥{{ row.total_price }}</div>
                </template>
              </table-column>
            </Table>
            <div class="table-tail">
              <p class="prompt">
                提示：如与商家沟通好价格调整，请联系或等待商家在后台调整价格后再支付。
              </p>
              <div class="remarks">
                <p class="text">备注信息：</p>
                <m-input
                  type="textarea"
                  v-model="item.remark"
                  :autosize="{ minRows: 6 }"
                  style="width: 700px"
                />
              </div>
              <div class="total">
                分项合计：<span class="keywords">￥{{ item.total_price }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="invoice">
          <div class="title-and-new">
            <p class="title">发票信息</p>
            <div class="new" @click="showInvoice = true">新增发票信息+</div>
          </div>
          <div class="list">
            <div
              class="item transition cursor"
              v-for="(item, index) in invoiceList"
              :key="index"
              @click="selectInvoice(item.id)"
              :class="invoiceChosen == item.id ? 'active' : ''"
            >
              <div class="title">
                发票抬头：{{ item.consignee }}
                <span v-if="item.is_default" class="default">默认发票</span>
              </div>
              <div class="number">税号：{{ item.tax_code }}</div>
              <m-button size="mini" type="light" width="111">{{ item.type == 0 ? "单位" : "个人" }}</m-button>
              <div class="checkbox">
                <div class="checkItem transition"></div>
              </div>
            </div>
          </div>
          <div class="send">
            <span class="text">发票寄送地址:</span>
            <radio-group v-model="invoice_add_type">
              <m-radio :label="0">公司地址</m-radio>
              <m-radio :label="1">其他地址</m-radio>
            </radio-group>
          </div>
          <div class="address-input">
            <m-input v-model="invoice_address" style="width: 355px" placeholder="请输入详细地址" />
          </div>
        </div>

        <div class="payment">
          <p class="title">支付方式</p>
          <radio-group v-model="payment">
            <m-radio :label="0">线上支付</m-radio>
            <m-radio :label="1">线下支付</m-radio>
          </radio-group>
          <PayMethods ref='PayMethods' @changeMethods='activeIndex=$event' v-if="payment === 0"/>
        </div>

        <div class="total">
          <div class="count">共<span class="keywords">{{ info.num }}</span>件</div>
          <div class="cost-and-pay">
            <div class="cost">应付总额：￥{{ info.total_price }}</div>
            <m-button type="light" width="122" @click="orderSubmit">
              <span class="pay-inner">提交订单</span>
            </m-button>
          </div>
        </div>

      </div>
    </div>
    <!-- 新增收获地址 -->
    <m-dialog
      :show-dialog.sync="showAddress"
      title="新增收货地址"
      width="752px"
    >
      <m-form
        ref="addressForm"
        :model="addressFormData"
        :rules="addressRules"
        label-width="120px"
        label-position="right"
      >
        <m-form-item prop="real_name" label="收货人：">
          <m-input v-model="addressFormData.real_name" />
        </m-form-item>
        <m-form-item prop="company" label="公司名称：">
          <m-input v-model="addressFormData.company" />
        </m-form-item>
        <m-form-item prop="province" label="目的地：">
          <div class="input-wrap">
            <v-distpicker
              class="addressChoose"
              @province="onChangeProvince"
              @city="onChangeCity"
              @area="onChangeArea"
              :province="addressFormData.province"
              :city="addressFormData.city"
              :area="addressFormData.district"
            ></v-distpicker>
          </div>
        </m-form-item>

        <m-form-item prop="detail" label="详细地址：">
          <m-input v-model="addressFormData.detail" />
        </m-form-item>
        <m-form-item prop="phone" label="手机号：">
          <m-input v-model="addressFormData.phone" maxlength="11" />
        </m-form-item>
        <m-form-item prop="phone" label="固定电话：">
          <m-input v-model="addressFormData.mobile" />
        </m-form-item>
        <m-form-item>
          <div style="display: flex; justify-content: center">
            <m-button width="220" @click="addAddress">保存</m-button>
          </div>
        </m-form-item>
      </m-form>
    </m-dialog>
    <!-- 新增发票地址 -->
    <m-dialog :show-dialog.sync="showInvoice" width="752px" title="新增发票信息">
      <m-form
        ref="invoiceForm"
        :model="invoiceFormData"
        :rules="invoiceRules"
        label-width="120px"
        label-position="right"
      >
        <m-form-item label="发票类型">
          <radio-group v-model="invoiceFormData.type">
            <m-radio :label="0">单位</m-radio>
            <m-radio :label="1">个人</m-radio>
          </radio-group>
        </m-form-item>
        <m-form-item prop="consignee" label="发票抬头：">
          <m-input v-model="invoiceFormData.consignee" />
        </m-form-item>
        <m-form-item prop="tax_code" label="税号：">
          <m-input v-model="invoiceFormData.tax_code" />
        </m-form-item>
        <m-form-item prop="bank" label="开户银行：">
          <m-input v-model="invoiceFormData.bank" />
        </m-form-item>
        <m-form-item prop="card_id" label="银行账号：">
          <m-input v-model="invoiceFormData.card_id" />
        </m-form-item>
        <m-form-item prop="company_address" label="单位地址：">
          <m-input v-model="invoiceFormData.company_address" />
        </m-form-item>
        <m-form-item prop="tel" label="电话号码：">
          <m-input v-model="invoiceFormData.tel" maxlength="11" />
        </m-form-item>
        <m-form-item>
          <div style="display: flex; justify-content: center">
            <m-button width="220" @click="handleAdd">保存</m-button>
          </div>
        </m-form-item>
      </m-form>
    </m-dialog>

  
  </div>
</template>

<script>
import MCheckbox from "@/components/common/m-checkbox/MCheckbox"
import { CheckboxGroup, RadioGroup, Table, TableColumn } from "element-ui"
import MInput from "@/components/common/m-input/MInput"
import MButton from "@/components/common/m-button/MButton"
import MRadio from "@/components/common/m-radio/MRadio"
import MDialog from "@/components/common/m-dialog/MDialog"
import MForm from "@/components/common/m-form/MForm"
import MFormItem from "@/components/common/m-form/MFormItem"
import MSelect from "@/components/common/m-select/MSelect"
import PayMethods from "@/components/PayMethods"
import {
  previewOrder,
  createOrder,
  getInvoice,
  getAddress,
  addEditAddress,
  addInvoice
} from "@/request/api"

export default {
  name: "Order",
  components: {
    MSelect,
    MFormItem,
    MForm,
    MDialog,
    MRadio,
    MButton,
    MInput,
    MCheckbox,
    CheckboxGroup,
    Table,
    TableColumn,
    RadioGroup,
    PayMethods
  },
  data() {
    return {
      info: "",
      cart_id: "",
      address_id: "",
      invoiceList: [],
      addressList: [],
      addressChosen: "",
      invoiceChosen: "",
      invoice_add_type: 0,
      invoice_address: "",
      merchant: "",
      orderNumber: "",
      products: [],
      checkList: [],
      send: "",
      sendAddress: "",
      payment: 0,
      showAddress: false,
      showInvoice: false,
      addressFormData: {},
      addressRules: {
        real_name: [{ required: true, message: "请输入完整", trigger: "blur" }],
        company: [{ required: true, message: "请输入完整", trigger: "blur" }],
        detail: [{ required: true, message: "请输入完整", trigger: "blur" }],
        phone: [{ required: true, message: "请输入完整", trigger: "blur" }],
      },
      provinceOptions: [{ label: "四川省", value: "Sichuan" }],
      cityOptions: [{ label: "成都市", value: "Chengdu" }],
      areaOptions: [{ label: "武侯区", value: "Wuhou" }],
      invoiceFormData: {},
      invoiceRules: {
        invoice: [{ required: true, message: "请输入完整", trigger: "blur" }],
        tax_code: [{ required: true, message: "请输入完整", trigger: "blur" }],
      },
      activeIndex: 1,
      is_cart: 1,
      code_url: null,
      isCodeUrl: false,
      group_order_id: ''
    }
  },
  created() {
    this.cart_id = this.$common.stringToArr(this.$route.query.cart_id)
    if(this.cart_id) this.cart_id = this.cart_id.toString()
    this.getInvoiceList()
    this.getAddressList()
    this.getInfo()
  },
  methods: {
    /** 提交订单 */
    orderSubmit() {
      if (!this.addressChosen) {
        return this.$toastVant.fail("请选择收货地址!")
      }
      let mark = {}
      if(this.info.list && this.info.list.length > 0) {
        this.info.list.forEach(item => {
        let id = item.mer_id
        let obj = { [id]: { value: item.remark || "" } }
        mark = Object.assign(mark, obj)
      })
     }
     if(this.payment === 1) this.activeIndex = 'offline'
      let data = {
        cart_id: this.cart_id,
        address_id: this.addressChosen,
        pay_type: this.activeIndex,
        invoice_add_type: this.invoice_add_type,
        invoice_address: this.invoice_address,
        invoice_id: this.invoiceChosen,
        mark: mark,
        is_cart: this.is_cart
      }
      this.$toastVant.loading("提交中")
      this.code_url = ''
      createOrder(data).then((res) => {
        if(this.activeIndex === 'alipay' && this.payment === 0) {
          this.$refs.PayMethods.zfbPay(res.data.result.config)
        }else if(this.activeIndex === 'weixin' && this.payment === 0) {
          this.$refs.PayMethods.wxPay(res.data.result)
        }
        if(this.payment === 1) {
          this.$router.push({
            path: "/category/paySuccess",
            query: { order_id: res.data.result.group_order_sn }
          })
        }
      })
    },
    // 当前选中的抬头发票的ID
    selectInvoice(id) {
      this.invoiceChosen = id
    },
    // 当前选中的收获地址的ID
    selectAddress(id) {
      this.addressChosen = id
    },
    // 获取用户信息
    getInfo() {
      let data = {
        cart_id: this.cart_id,
        is_cart: this.is_cart
      }
      previewOrder(data).then((res) => {
        this.info = res.data || {}
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 获取抬头发票的列表
    getInvoiceList() {
      getInvoice()
        .then((res) => {
          this.invoiceList = res.data.data
          if (this.invoiceList.length > 0) {
            this.invoiceChosen = this.invoiceList[0].id
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    /** 获取地址列表*/
    getAddressList() {
      getAddress()
        .then((res) => {
          this.addressList = res.data.list.data
          if (this.addressList.length > 0) {
            this.addressChosen = this.addressList[0].address_id
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    // 选择省市区
    onChangeProvince(e) {
      this.addressFormData.province = e.value
    },
    onChangeCity(e) {
      this.addressFormData.city = e.value
    },
    onChangeArea(e) {
      this.addressFormData.district = e.value
    },
    // 新增地址
    addAddress() {
      let that = this;
      this.$refs.addressForm.$refs.mForm.validate((res) => {
        if (res) {
          that.$toastVant.loading("请稍后")
          addEditAddress(that.addressFormData)
            .then(() => {
              setTimeout(function () {
                that.$toastVant.success("添加成功!")
                that.getAddressList()
                that.showAddress = false
              }, 500)
            })
            .catch((err) => {
              this.$message.error(err.message)
            })
        }
      })
    },
    // 新增抬头发票
    handleAdd() {
      const that = this
      this.$refs.invoiceForm.$refs.mForm.validate((res) => {
        if (res) {
          that.$toastVant.loading("请稍后")
          addInvoice(this.invoiceFormData)
            .then(() => {
              setTimeout(function () {
                that.$toastVant.success("添加成功!")
                that.getInvoiceList()
                that.showInvoice = false
              }, 500)
            }).catch((err) => {
              this.$message.error(err.message)
            })
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/assets/style/common.scss";

.local {
  color: #656565;
  margin-bottom: 20px;
}

.dialog{
  text-align: center;
  /deep/ .el-dialog__body {
    padding: 10px !important;
  }
  .qrCodeUrl {
      display: flex !important;
      justify-content: center !important;
      align-items: center !important;
      width: 170px;
      height: 170px;
      margin: 10px auto;
  }
  .title{
    color: #e38b2e;
    font-weight: 400;
    font-size: 16px;
    margin: 10px 0;
  }
  .btns {
    display: flex;
    justify-content: space-around;
    align-items: center;
    p {
      width: 150px;
      height: 30px;
      line-height: 30px;
      margin: 0 10px;
      border-radius: 10px;
      background: #fff;
      border: 1px solid #e38b2e;
    }
    p:nth-child(1) {
      border: 1px solid #e38b2e;
      color: #fff;
      background: #e38b2e;
      cursor: pointer;
    }
  }
}

.local img {
  margin-right: 10px;
}

.input-wrap {
  width: 435px;
  display: flex;
  justify-content: space-between;
  .addressChoose {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}
/deep/.distpicker-address-wrapper select {
  width: 100%;
  height: 45px;
  background-color: #f3f4f8;
  border: solid 1px #e9e9e9;
  border-radius: 10px;
  position: relative;
}
/deep/ .distpicker-address-wrapper label {
  display: block;
  width: 32%;
}

.order {
  padding: 30px 0 80px 0;

  .content {
    margin-top: 50px;
    font-size: 16px;

    .receiver {
      padding: 65px 50px;
      background-color: #fff;
      font-size: 16px;
      color: #666;
      margin-bottom: 50px;

      .title-and-new {
        display: flex;
        justify-content: space-between;
        margin-bottom: 30px;

        .title {
          font-size: 20px;
          color: #000;
          font-weight: bold;
        }

        .new {
          color: $theme-color-1;
          cursor: pointer;
        }
      }

      .address-list {
        background-color: rgb(243, 244, 247);
        padding: 15px;
        margin: -10px;

        .item {
          width: calc((100% - 60px) / 3);
          margin: 10px;
          height: 167px;
          display: block;
          float: left;
          padding: 10px;
          padding-right: 50px;
          background-color: #fff;
          position: relative;

          > div:not(:last-of-type) {
            margin-bottom: 8px;
          }

          .name {
            position: relative;
            display: inline-block;
          }

          .default {
            position: absolute;
            right: -84px;
            width: 74px;
            height: 22px;
            text-align: center;
            line-height: 22px;
            font-size: 14px;
            border-radius: 11px;
            color: #fff;
            background-color: $theme-color-1;
          }

          .checkbox {
            position: absolute;
            right: 10px;
            top: 10px;
          }

          .checkItem {
            width: 20px;
            height: 20px;
            border: 1px solid #ccc;
            margin: 0 auto;
            cursor: pointer;
            border-radius: 5px;
            position: relative;
          }
        }

        .active {
          background: $theme-color-1;
          color: #fff;

          .default {
            background: #fff;
            color: $theme-color-1;
          }

          .checkItem {
            background: #fff;
            border-color: #fff;
          }

          .checkItem:after {
            content: "";
            border: 2px solid $theme-color-1;
            border-left: 0;
            border-top: 0;
            height: 9px;
            left: 6px;
            position: absolute;
            top: 2px;
            transform: rotate(45deg);
            width: 4px;
            transition: transform 0.15s ease-in 0.05s;
            transform-origin: center;
          }
        }
      }

      .address-empty {
        background-color: rgb(243, 244, 247);
        padding: 15px;
        min-height: 210px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }

    .checklist {
      padding: 65px 50px;
      background-color: #fff;
      font-size: 16px;
      color: #666;
      margin-bottom: 50px;

      .title {
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 30px;
      }

      .item {
        &:not(:last-of-type) {
          margin-bottom: 50px;
        }

        .merchant-and-number {
          display: flex;
          padding: 15px;
          border: 2px solid #f3f4f7;

          .merchant {
            margin-right: 50px;
          }
        }

        .table-head {
          /deep/ .el-table__body-wrapper {
            height: 0;
          }

          /deep/ th {
            color: #666;
            background-color: #f3f4f7;
          }
        }

        .table-name {
          display: flex;
          align-items: center;

          .pic {
            width: 140px;
            height: 140px;
            margin-right: 15px;
          }
        }

        .table-total {
          color: $theme-color-1;
        }

        .table-tail {
          border: 1px solid #ebeef5;
          border-top: none;
          padding: 30px 20px;

          .prompt {
            font-size: 14px;
            color: #969696;
            margin-bottom: 30px;
          }

          .remarks {
            margin-bottom: 30px;

            .text {
              margin-bottom: 15px;
            }
          }

          .total {
            font-size: 18px;

            .keywords {
              font-size: 20px;
              color: #000;
              font-weight: bold;
            }
          }
        }
      }
    }

    .invoice {
      padding: 65px 50px;
      font-size: 16px;
      color: #666;
      background-color: #fff;
      margin-bottom: 50px;

      .title-and-new {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;

        .title {
          font-size: 20px;
          font-weight: bold;
          margin-right: 50px;
        }

        .new {
          color: $theme-color-1;
          cursor: pointer;
        }
      }

      .list {
        margin: -10px;
        margin-bottom: 30px;

        .item {
          width: calc((100% - 60px) / 3);
          height: 147px;
          margin: 10px;
          padding: 15px;
          padding-right: 50px;
          background-color: rgb(243, 244, 247);
          display: inline-flex;
          flex-direction: column;
          justify-content: space-between;
          position: relative;

          .default {
            display: inline-block;
            width: 74px;
            margin-left: 4px;
            height: 22px;
            text-align: center;
            line-height: 22px;
            font-size: 14px;
            border-radius: 11px;
            color: #fff;
            background-color: $theme-color-1;
          }

          .checkbox {
            position: absolute;
            top: 10px;
            right: 10px;
          }

          .checkItem {
            width: 20px;
            height: 20px;
            border: 1px solid #ccc;
            margin: 0 auto;
            cursor: pointer;
            border-radius: 5px;
            position: relative;
          }
        }

        .active {
          background: $theme-color-1;
          color: #fff;

          .default {
            background: #fff;
            color: $theme-color-1;
          }

          .checkItem {
            background: #fff;
            border-color: #fff;
          }

          .checkItem:after {
            content: "";
            border: 2px solid $theme-color-1;
            border-left: 0;
            border-top: 0;
            height: 9px;
            left: 6px;
            position: absolute;
            top: 2px;
            transform: rotate(45deg);
            width: 4px;
            transition: transform 0.15s ease-in 0.05s;
            transform-origin: center;
          }
        }
      }

      .send {
        margin-bottom: 30px;

        .text {
          margin-right: 30px;
        }
      }
    }

    .payment {
      padding: 65px 50px;
      background-color: #fff;
      font-size: 16px;
      color: #666;

      .title {
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 30px;
      }

      .payment-list {
        margin-top: 15px;
        // padding-bottom: 40px;
        position: relative;

        li,
        li img {
          width: 173px;
          height: 59px;
        }

        li {
          float: left;
          margin-right: 14px;
          border: 1px solid #e7e7e7;
          list-style: none;
          cursor: pointer;
        }

        li.active {
          border: 1px solid #e38b2e;
        }
      }

      .clearfix:before {
        content: " ";
        display: table;
      }
    }

    .qrCodeUrl {
      display: block;
      width: 173px;
      height: 173px;
      border: 1px solid #e3e3e3;
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      margin: 20px 0 0 187px;
    }

    > .total {
      padding: 10px 15px;
      background-color: $theme-color-1;
      color: #fff;
      font-size: 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .count {
        .keywords {
          font-size: 20px;
          margin: 0 10px;
        }
      }

      .cost-and-pay {
        display: flex;
        align-items: center;

        .cost {
          font-weight: bold;
          font-size: 20px;
          margin-right: 30px;
        }

        .pay-inner {
          font-size: 18px;
          font-weight: bold;
          color: $theme-color-1;
        }
      }
    }
  }
}
</style>
